import Vue from 'vue';
import app from './App.vue';
import MintUI from 'mint-ui';
import 'mint-ui/lib/style.css';
Vue.use(MintUI);
import './lib/mui/css/mui.min.css';
import './lib/mui/css/icons-extra.css';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import router from './router.js';
import Vuex from 'vuex';
Vue.use(Vuex);

var car = JSON.parse(localStorage.getItem('car') || '[]');
var store = new Vuex.Store({
    state: {
        car: car
    },
    mutations: {
        addGoods(state,goodsInfo) {
            var flag = false;
            state.car.some(item=>{
                if(item.id == goodsInfo.id) {
                    item.count += parseInt(goodsInfo.count);
                    flag = true;
                    return true;
                }
            })
            if(!flag) {
                state.car.push(goodsInfo);
            }
            localStorage.setItem('car',JSON.stringify(state.car));
        },
        updateGoods(state,goodsInfo) {
            state.car.some(item=>{
                if(item.id == goodsInfo.id) {
                    item.count = parseInt(goodsInfo.count);
                    return true;
                }
            })
            localStorage.setItem('car',JSON.stringify(state.car));
        },
        updateSelect(state,obj) {
            state.car.forEach(item=>{
                if(item.id == obj.id) {
                    item.selected = obj.selected;
                }
            })
            localStorage.setItem('car',JSON.stringify(state.car));
        }
    },
    getters: {
        getNewCount(state) {
            var sum = 0;
            state.car.forEach(item=>{
                sum += item.count;
            })
            return sum;
        },
        getAllCountAndPrice(state) {
            var o = {
                selectCount: 0,
                totalPrice: 0
            };
                state.car.forEach(item=>{
                if(item.selected == true) {
                    o.selectCount += item.count;
                    o.totalPrice += (item.count * item.price);
                }
            })
            return o;
        }
    }
});

var vue = new Vue({
    el: '#app',
    render:c=>c(app),
    router,
    store
});